package logic

import (
	"context"
	"strings"

	"mall/common/errorx"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateMemberLevelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateMemberLevelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateMemberLevelLogic {
	return &UpdateMemberLevelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateMemberLevelLogic) UpdateMemberLevel(in *backend.UpdateMemberLevelReq) (*backend.UpdateMemberLevelResp, error) {
	if in.Id == 0 {
		return nil, errorx.Status(errorx.ERROR_MEMBER_LEVEL_ID_REQUIRED, "")
	}

	name := strings.TrimSpace(in.Name)
	if len(name) == 0 {
		return nil, errorx.Status(errorx.ERROR_MEMBER_LEVEL_NAME_REQUIRED, "")
	}

	filterMap := make(map[string]map[string][]any)
	filterMap[model.MemberLevelColumns.Name] = map[string][]any{
		"equalTo": {name},
	}
	var pageSize int64 = 2
	list, _, err := l.svcCtx.MemberLevel.GetList(l.ctx, model.M{
		"pageSize": pageSize,
		"select":   ",",
	}, -1, filterMap)
	if err != nil {
		return nil, err
	}

	count := len(list)
	if count > 1 {
		return nil, errorx.Status(errorx.ERROR_MEMBER_LEVEL_NAME_EXISTS, "")
	}

	if count == 1 && list[0].MemberLevelID != uint64(in.Id) {
		return nil, errorx.Status(errorx.ERROR_MEMBER_LEVEL_NAME_EXISTS, "")
	}

	ml, err := l.svcCtx.MemberLevel.FindOne(l.ctx, in.Id, []string{})
	if err != nil {
		return nil, err
	}

	ml.Name = in.Name
	ml.Slug = in.Slug
	ml.Description = in.Desc
	ml.ThumbnailID = uint64(in.MediaId)
	ml.ThumbnailURL = in.MediaUrl
	ml.GrowthThreshold = uint(in.Integral)
	ml.PrivilegeMemberPrice = uint8(in.WithMemberPrice)
	ml.PrivilegePromotion = uint8(in.WithPromotion)
	ml.PrivilegeFreeFreight = uint8(in.WithFreeFreight)
	ml.PrivilegeComment = uint8(in.WithComment)
	ml.PrivilegeSignIn = uint8(in.WithSignIn)
	ml.PrivilegeBirthday = uint8(in.WithBirthday)
	ml.FreeFreightThreshold = uint64(in.FreeFreight)
	ml.GrowthPerComment = uint(in.IntegralForComment)
	ml.TaskCount = uint(in.TaskCount)
	ml.IsDefault = uint8(in.IsDefault)
	_, err = l.svcCtx.MemberLevel.Update(l.ctx, ml)
	if err != nil {
		return nil, err
	}

	return &backend.UpdateMemberLevelResp{}, nil
}
